<script setup lang="ts">
  import SingleAddress from '@/components/business/address/single-address/SingleAddress.vue'
  import CustomTextarea from './CustomTextarea.vue'
  import { PropType, ref, watch } from 'vue'

  defineOptions({
    name: 'OrderCustomFormAddress',
  })

  const props = defineProps({
    modelValue: {
      type: Object as PropType<{
        province: string
        city: string
        area: string
        town: string
        address: string
      }>,
      default: () => {
        return {
          province: '',
          city: '',
          area: '',
          town: '',
          address: '',
        }
      },
    },
    disabled: {
      type: Boolean,
      default: () => false,
    },
  })

  const emits = defineEmits<{
    (
      e: 'update:modelValue',
      value: { province: string; city: string; area: string; town: string; address: string },
    ): void
  }>()

  // 地址选择绑定
  const address = ref({
    province: '',
    city: '',
    area: '',
    town: '',
  })

  // 详细地址绑定
  const detailAddress = ref('')

  // 事件发射调用
  const emitsCall = () => {
    emits('update:modelValue', {
      ...address.value,
      address: detailAddress.value,
    })
  }

  // 地址选择更新事件
  const handleSingleAddressChange = (_address: typeof address.value) => {
    address.value = _address
    emitsCall()
  }

  watch(
    () => props.modelValue,
    (value) => {
      address.value = {
        province: value.province,
        city: value.city,
        area: value.area,
        town: value.town,
      }
      detailAddress.value = value.address
    },
    { deep: true },
  )
</script>

<template>
  <div class="order-custom-form-address">
    <single-address
      :disabled="props.disabled"
      :address="address"
      @change="handleSingleAddressChange"
    />
    <custom-textarea v-model="detailAddress" :disabled="props.disabled" @input="emitsCall" />
  </div>
</template>

<style scoped lang="scss">
  .order-custom-form-address {
    display: flex;
    flex-direction: column;
    row-gap: 4px;
    width: 100%;
  }
</style>
